#include "getonlinefriendresponse.h"

#include <QDebug>

GetOnlineFriendResponse::Item::Item(qint64 id, qint64 mobileTime, qint64 webTime)
    : m_id(id)
    , m_mobileTime(mobileTime)
    , m_webTime(webTime)
{
}

GetOnlineFriendResponse::GetOnlineFriendResponse(QObject *parent)
    : JSONResponse(parent)
{
}

GetOnlineFriendResponse::~GetOnlineFriendResponse()
{
    //qDeleteAll(m_items);
}

void GetOnlineFriendResponse::clearData()
{
    qDeleteAll(m_items);
    m_items.clear();
}



void GetOnlineFriendResponse::parse(const QVariant &data)
{
    if (data.type() != QVariant::Map) {
        setError(Network::Response::Property, QString("The \"data\" field isn't compatible"));
        return;
    }

    QVariantMap map = data.toMap();

    /*
    if (!map.contains("tot")) {
        setError(Network::Response::Property, QString("The \"tot\" field is missing"));
        return;
    }

    QVariant total = map.value("tot");
    if (total.type() != QVariant::Int) {
        setError(Network::Response::Property, QString("The \"tot\" field isn't compatible"));
        return;
    }
    */

    if (!map.contains("list")) {
        setError(Network::Response::Property, QString("The \"list\" field is missing"));
        return;
    }

    QVariant list = map.value("list");
    if (list.type() != QVariant::List) {
        setError(Network::Response::Property, QString("The \"list\" field isn't compatible"));
        return;
    }

    parseList(list.toList());

}

void GetOnlineFriendResponse::parseList(const QVariantList &list)
{
    foreach (QVariant item, list) {
        if (item.type() != QVariant::Map)
            continue;

        QVariantMap map = item.toMap();
        if (!map.contains("uid"))
            continue;

        bool ok;
        QVariant idVariant = map.value("uid");
        qint64 id = idVariant.toString().toLongLong(&ok);
        if (!ok)
            continue;

        if (!map.contains("timemobile"))
            continue;

        QVariant mobileTimeVariant = map.value("timemobile");
        qint64 mobileTime = mobileTimeVariant.toString().toLongLong(&ok);
        if (!ok)
            continue;

        if (!map.contains("timeweb"))
            continue;

        QVariant webTimeVariant = map.value("timeweb");
        qint64 webTime = webTimeVariant.toString().toLongLong(&ok);
        if (!ok)
            continue;

        m_items.append(new Item(id, mobileTime, webTime));
    }
}

